const { obd_collection } = require('../config')
const { staff_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const pick = require('lodash/pick')
// 返回
exports.main = async (event, context) => {
    var accountArr;
    // console.log(111111, event);
    // 指定账号则更新部分，否则更新全部
    if (event.hasOwnProperty('account') && event.account != []) {
        accountArr = event.account;
    } else {
        staffData = await db.collection(staff_collection).where({ status: _.neq('离职') ,position:"全职装维"}).limit(1000).orderBy('account', 'asc').get();
        if (staffData.data && staffData.data.length) {
            accountArr = staffData.data.map(i => {
                const item = pick(i, ['account']);
                return item.account;
            })
        }
    }
    // return accountArr.length
    // console.log(222222, accountArr);
    // 1.循环每个员工
    i = 0;
    // staffData.data=[{"account":"dwluoyonglian","name":"罗永练"}];
    const failAccounts = [];
    for (account of accountArr) {
        i++;
        console.log(accountArr.length,i, '开始更新员工：' + account)
        // 2.在obd信息表中查找到该员工账号的obd，获取所有obd的经纬度；无经obd则下一个
        const obdData = await db.collection(obd_collection).where({ staff: account }).limit(10000).get();
        // console.log(323333,obdData.data.length,obdData.data.length != 0)
        if (obdData.data.length != 0) {
            allObdLongLat = [];
            userCount = 0;
            for (obd of obdData.data) {
                if (obd.long && obd.lat) {
                    allObdLongLat.push({ lng: Number(obd.long), lat: Number(obd.lat) });
                    userCount += parseInt(obd.portOccupy);
                }
            }
            // return allObdLongLat;
            // console.log('2所有经纬度：', allObdLongLat)
            obdCount = obdData.data.length;
            // 3.获取所有obd的经纬度之后，计算出面积周长，并更新到该员工信息表那里，下一个
            // 凸包点经纬度
            allObdLongLat = delWrongData(allObdLongLat);
            //console.log("经纬度",allObdLongLat[0])
            var mapData = cal(allObdLongLat);
            // console.log('3面积周长：' , mapData)
            obdLongLat = mapData.hullPoints;
            let area = Number((mapData.area * 10000).toFixed(2));
            let perimeter = Number(mapData.perimeter.toFixed(2));
            // console.log('账号，面积',account, area)
            upRes = await db.collection(staff_collection).where({ account: account }).update({
                lineLongLat: obdLongLat,
                obdLongLat: allObdLongLat,
                area: area,
                userCount: userCount,
                allObdCount: allObdLongLat.length,
                mapObdCount: obdLongLat.length,
                perimeter: perimeter,
                center: mapData.center,
            })
            if (!upRes) {
                failAccounts.push(account);
                console.log(i, account + '更新失败')
            }
        } else {
            console.log(i, '不存在' + account + '的obd')
        }
    }
    return { sumAccounts: accountArr.length, failAccounts: failAccounts }
    // 保存接口日志
    // let apiLog = {
    //     "target": event.target,
    // }
}
function delWrongData(allObdLongLat) {
    // 计算所有经纬度的平均值
    let lngSum = 0;
    let latSum = 0;
    allObdLongLat.forEach(item => {
        lngSum += item.lng;
        latSum += item.lat;
    });

    const averageLng = lngSum / allObdLongLat.length;
    const averageLat = latSum / allObdLongLat.length;
    const level = 0.1;
    // 过滤掉异常数据
    const filteredData = allObdLongLat.filter(item => {
        return Math.abs(item.lng - averageLng) <= level && Math.abs(item.lat - averageLat) <= level;
    });

    return filteredData;
    // 1.创建一个delWrongData方法，删除掉经纬度数据变量allObdLongLat里的异常数据，allObdLongLat里面的数据是例如 [{"lng":110.921983,"lat":21.676655},{"lng":110.949211,"lat":21.679529},{"lng":110.945905,"lat":21.685037},{"lng":110.932512,"lat":21.672313}]的数据格式（值仅供举例的），数据中lng是经度，lat是纬度，先算出allObdLongLat数据里所有经度和纬度的平均值，然后allObdLongLat中每个数据项的经度或纬度比经度或纬度平均值少0.1或者少-0.1，视为异常数据，从allObdLongLat变量中剔除，返回剔除后的allObdLongLat
}
function cal(allObdLongLat) {
    const convexHull = require('convex-hull');
    const deg2rad = (deg) => deg * (Math.PI / 180); // 将角度转换为弧度

    // 转换数据格式为凸包库需要的形式
    const points = allObdLongLat.map(p => [parseFloat(p.lng), parseFloat(p.lat)]);
    // 计算凸包
    const hull = convexHull(points);

    // 创建一个空数组来存储凸包上的点
    let hullPoints = [];

    // 添加每条边的起始点
    for (let i = 0; i < hull.length; i++) {
        let idx = hull[i][0]; // 获取边的起始点索引
        hullPoints.push({ lng: points[idx][0], lat: points[idx][1] });
    }

    // 确保多边形闭合，检查第一个和最后一个点是否相同，如果不相同，添加第一个点到末尾
    if (hullPoints[0].lng !== hullPoints[hullPoints.length - 1].lng ||
        hullPoints[0].lat !== hullPoints[hullPoints.length - 1].lat) {
        hullPoints.push(hullPoints[0]);
    }

    // 计算周长
    let perimeter = 0;
    for (let i = 0; i < hullPoints.length - 1; i++) {
        const dLat = deg2rad(hullPoints[i + 1].lat - hullPoints[i].lat);
        const dLng = deg2rad(hullPoints[i + 1].lng - hullPoints[i].lng);
        const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(deg2rad(hullPoints[i].lat)) * Math.cos(deg2rad(hullPoints[i + 1].lat)) *
            Math.sin(dLng / 2) * Math.sin(dLng / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        perimeter += 6371 * c; // 地球平均半径约为6371公里
    }

    // 计算面积 (使用Shoelace公式)
    let area = 0;
    for (let i = 0; i < hullPoints.length - 1; i++) {
        area += hullPoints[i].lng * hullPoints[i + 1].lat;
        area -= hullPoints[i + 1].lng * hullPoints[i].lat;
    }
    area = Math.abs(area / 2);

    // 计算中心点（质心）
    let centerX = 0;
    let centerY = 0;
    hullPoints.forEach(point => {
        centerX += point.lng;
        centerY += point.lat;
    });
    centerX /= hullPoints.length;
    centerY /= hullPoints.length;

    // 输出结果
    // console.log('Hull Points:', hullPoints);
    // console.log('Perimeter:', perimeter);
    // console.log('Area:', area);
    // console.log('Center Point:', { lng: centerX, lat: centerY });

    return { 'hullPoints': hullPoints, 'perimeter': perimeter, 'area': area, 'center': { lng: centerX, lat: centerY } };
}
// {"obdLongLat":[{"lng":"110.921983","lat":"21.676655"},{"lng":"110.949211","lat":"21.679529"},{"lng":"110.945905","lat":"21.685037"},{"lng":"110.932512","lat":"21.672313"},{"lng":"110.930776","lat":"21.681453"},{"lng":"110.917828","lat":"21.661672"},{"lng":"110.929164","lat":"21.693888"},{"lng":"110.942564","lat":"21.672544"},{"lng":"110.939894","lat":"21.68074"}]用nodejs处理我给出的这些x、y轴点数据（lng对应x轴，lat对应y轴），对他们进行排序、筛选，让处理后的x、y点的点连接起来后形成一个闭合的只有凸包没有凹包的多边形，这个要求意味着可以舍弃部分不符合要求的点，请您按照要求给出详细的nodejs代码

// 有必要给计算面积功能做日志记录吗？如果